package com.xfcycle.zebrabikegp.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.assist.BlueToothAssist;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.constant.WebConstant;
import com.xfcycle.zebrabikegp.util.EncryptStringUtil;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;
import com.xfcycle.zebrabikegp.util.HandleDataBySharePreferencesUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 密码找回窗体,修改密码
 */
public class FindPasswordPasswordActivity extends RootActivity {

    private EditText et_fpw_password_first;
    private EditText et_fpw_password_confirm;
    private TextView tv_fpw_done;
    private ImageView iv_findPassword_password_back;

    private String email_address;
    private String captcha;

    private String passwordfirst;
    private String passwordConfirm;

    private HandleDataBySharePreferencesUtil handleDataBySharePreferencesUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_findpassword_password);

        //获取上一个页面传递的邮箱地址
        Bundle bundle = this.getIntent().getExtras();
        email_address = bundle.getString("email_address");
        captcha = bundle.getString("captcha");

        initView();
        initViewListener();
    }

    /**
     * 初始化组件
     */
    public void initView() {
        iv_findPassword_password_back = (ImageView) findViewById(R.id.iv_findpassword_password_back);

        et_fpw_password_first = (EditText) findViewById(R.id.et_findpassword_password_first);
        et_fpw_password_confirm = (EditText) findViewById(R.id.et_findpassword_password_confirm);
        tv_fpw_done = (TextView) findViewById(R.id.tv_findpassword_done);

        handleDataBySharePreferencesUtil = HandleDataBySharePreferencesUtil.getInstance(this);
    }

    /**
     * 组件监听事件添加
     */
    public void initViewListener() {

        //回退按钮事件
        iv_findPassword_password_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeActivity();
            }
        });

        //修改密码
        tv_fpw_done.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Editable etPasswordFirst = et_fpw_password_first.getText();
                Editable etPasswordConfirm = et_fpw_password_confirm.getText();

                if(null == etPasswordFirst || "".equals(etPasswordFirst.toString()) || null == etPasswordConfirm || "".equals(etPasswordConfirm.toString())){
                    Toast.makeText(FindPasswordPasswordActivity.this.getApplicationContext(), ToastConstant.PASSWORD_CAN_NOT_EMPTY, Toast.LENGTH_SHORT).show();
                }

                passwordfirst = etPasswordFirst.toString();
                passwordConfirm = etPasswordConfirm.toString();

                if(!passwordfirst.equals(passwordConfirm)){
                    Toast.makeText(FindPasswordPasswordActivity.this, ToastConstant.TWO_PASSWORD_DIFFERENT, Toast.LENGTH_SHORT).show();
                }

                //判断验证码是否符合
                Map<String,String> params_reset_password = new HashMap<>();
                params_reset_password.put(WebConstant.RESET_PASSWORD_PATH_EMAIL,email_address);
                params_reset_password.put(WebConstant.RESET_PASSWORD_PATH_PASSWORD, EncryptStringUtil.getMd5(passwordfirst));
                params_reset_password.put(WebConstant.RESET_PASSWORD_PATH_CODE,captcha);
                new GetJsonFromWebJob(WebConstant.RESET_PASSWORD_PATH,WebConstant.PUT,params_reset_password,REQUEST_SIGN_RESETPASSWORD,FindPasswordPasswordActivity.this).start();
            }
        });
    }

    /**
     * 处理从网络获取的数据
     *
     * @param webMsg 获取到的网络信息
     */
    @Override
    public void dealDataFromWeb(Message webMsg) {
        super.dealDataFromWeb(webMsg);

        String webResult = webMsg.obj.toString();
        int webSign = webMsg.what;

        //判断验证码已过期
        if (webResult.contains("verification code expired")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.CAPTCHA_EXPIRE, Toast.LENGTH_SHORT).show();
            activityChange(FIND_PASSWORD_ADDRESS_ACTIVITY, null, null);
        }
        //判断验证码不匹配
        if (webResult.contains("verification code mismatched")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.CAPTCHA_MISMATCH, Toast.LENGTH_SHORT).show();
            activityChange(FIND_PASSWORD_ADDRESS_ACTIVITY, null, null);
        }
        //判断用户不存在
        if (webResult.contains("none user")) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.ACCOUNT_NOT_EXIST, Toast.LENGTH_SHORT).show();
            activityChange(FIND_PASSWORD_ADDRESS_ACTIVITY, null, null);
        }

        //修改密码成功，跳转到登录界面
        if (REQUEST_SIGN_RESETPASSWORD == webSign && "".equals(webResult)) {
            //将数据存储到SharePreferences中
            Map<String,String> params_register_info = new HashMap<>();
            params_register_info.put("email",email_address);
            params_register_info.put("password",passwordfirst);
            handleDataBySharePreferencesUtil.putDateIntoSharePre(APP_INFO_SP_NAME,params_register_info);

            activityChange(LOGIN_ACTIVITY, null, null);
        }

        //判断在其他设备登陆
        if (webMsg.obj.toString().contains("you are signed in at another location") && REQUEST_SIGN_LOGOUT != webMsg.what) {
            //断开连接
            HandleDataByBLEUtil.disConnectDevice();
            //改变蓝牙辅助判断类的值
            BlueToothAssist.isConnect = false;
            BlueToothAssist.currentConnectBikeId = null;

            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(ToastConstant.DIALOG_WARNING);
                builder.setMessage(ToastConstant.OTHER_DEVICE_LOGIN);

                builder.setPositiveButton(ToastConstant.DIALOG_I_KNOW, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //回到登录界面
                        activityChange(LOGIN_ACTIVITY, null, null);
                        HandleDataByBLEUtil.disConnectDevice();
                    }

                });
                //展示提示框
                builder.create().show();
            }catch (Exception e){
                Toast.makeText(this.getApplicationContext(),ToastConstant.OTHER_DEVICE_LOGIN, Toast.LENGTH_LONG).show();
                activityChange(LOGIN_ACTIVITY, null, null);
                HandleDataByBLEUtil.disConnectDevice();
            }
        }
    }
}
